var imagemotionLock = false;
var imagerunMotionLock = false;
var imagemotionQuery = new Array;
var imagerun = '';
var imagelastClickTime = 0;

var imagecheckTime = function() { 
    timestamp = Number(new Date());
    if (imagelastClickTime == 0) {
        imagelastClickTime = timestamp;
        return true;
    }
    result = (((timestamp - imagelastClickTime) > (2 * vidtest.speed)) );
    imagelastClickTime = timestamp;
    return result;
}

var imagerunSleepedMotion = function() {
    while (imagemotionQuery.length > 0){        
        imagerun = imagemotionQuery.pop();
        if (imagerun == 'right'){

            // Sleeped right
            if (vidtest.position == (vidtest.count)){
                $('scroll-line').style.left = '0';
                vidtest.position = 0;
            }
            imagerunMotionLock = true;
            $awQ('div#scroll-line').animate({left: '-=' + vidtest.pixScroll + 'px'}, vidtest.speed / 4, function() {imagerunMotionLock = false;});
            vidtest.position ++;
            vidtest.updatePager();

        } else if(imagerun == 'left') {
            
            // Sleeped left
            if (vidtest.position == 0){
                vidtest.position = (vidtest.count);
                $('scroll-line').style.left = '-' + (vidtest.position * vidtest.pixScroll)  + 'px';
            }
            imagerunMotionLock = true;
            $awQ('div#scroll-line').animate({left: '+=' + vidtest.pixScroll + 'px'}, vidtest.speed / 4, function() {imagerunMotionLock = false;});
            vidtest.position --;
            vidtest.updatePager();
        }
    }
    imagemotionLock = false;
}
var AWImagetest = Class.create();
AWImagetest.prototype = {
    initialize: function( width, height, pixScroll, perPage, count) {
        this.speed = 210;
        this.formShow = false;
        this.images = new Array;
        this.playerWidth = width;
        this.playerHeight = height;
        this.pixScroll = pixScroll;
        this.position = 0;
        this.page = 0;
        // this.perPage = perPage;
        this.count = count;
        this.detailTemplate = '';
        this.templateSyntax = /(^|.|\r|\n)({{(\w+)}})/;
        this.template = undefined;
        this.ajaxUrl = '';
        this.rateId = '';

        //reinit this.perPage
        this.initPerPage();

        this.initScroller();
    
    },

    initPerPage: function(){
        var items = jQuery('div.aw-imagetest-imageitem');

        if (items[0]!=undefined){

            var itemWidth = $(items[0]).getWidth();
            var marginRight = parseInt($(items["0"]).getStyle('margin-right').replace('px', ''));
            var marginLeft =  parseInt($(items["0"]).getStyle('margin-left').replace('px', ''));

            var fullItemWidths = itemWidth+marginRight+marginLeft;

            var itemsCount = items.size();

            var scrollFrameWidth =   $('aw-imagetest-scroll-frame-id').getWidth();

            var countOfThumbsForLayout =  Math.round(scrollFrameWidth/fullItemWidths);

            this.perPage = countOfThumbsForLayout;

            var buttons = jQuery('div.image-page-button');      

            var reduceButtonsCountTill = 1;

            if (this.count>countOfThumbsForLayout){

                reduceButtonsCountTill = Math.ceil(this.count/countOfThumbsForLayout);
            }

            for (var i = reduceButtonsCountTill-1; i < buttons.size(); i++){
                if (i == reduceButtonsCountTill-1 && reduceButtonsCountTill != 1) {
                    $(buttons[i]).addClassName('last');
                }
                else{
                    $(buttons[i]).hide();
                }
            }

            //disables navigation arrows
            if (countOfThumbsForLayout>=itemsCount){              
                $("image-sbt-right").addClassName('disabled');
                $("image-sbt-left").addClassName('disabled');
            }
        }
    },

    initScroller: function(){
        var items = jQuery('div.aw-imagetest-imageitem');
        if (items.length > this.perPage){
            for (var i = 0; i < this.perPage; i++){
                jQuery('div#image-scroll-line').append('<div id="' + items[i].id + '" class="aw-imagetest-imageitem">' + items[i].innerHTML + '</div>');
            }
        }
    },
    show: function(element){
        new Effect.Opacity(element, {from: 0, to: 1, duration: this.speed});
    },
    hide: function(element){
        new Effect.Opacity(element, {from: 1, to: 0, duration: this.speed});

    },
    toogleForm: function(){
        
        if (this.count == 0){            
            this.formShow = true;
            $('image-uploadform-content').style.display = this.formShow ? 'block' : 'none';
            return false;
        }

        if (this.formShow){
            this.formShow = false;
        } else {
            this.formShow = true;            
        }
        $('image-uploadform-content').style.display = this.formShow ? 'block' : 'none';
    },
    scrollRight: function(obj){
        if (jQuery(obj).hasClass('disabled')) {return false;}

        if (imagemotionLock){
            if ((imagemotionQuery.length < 1) && imagecheckTime()){
                
                imagemotionQuery.push('right');
            }
            return false;
        }

        if (this.position == (this.count)){
            $('image-scroll-line').style.left = '0';
            this.position = 0;
        }

        imagemotionLock = true;
        jQuery('div#image-scroll-line').animate({left: '-=' + this.pixScroll + 'px'}, this.speed, function() {imagerunSleepedMotion();});
        this.position ++;
        this.updatePager();
    },
    scrollLeft: function(obj){
        if (jQuery(obj).hasClass('disabled')) {return false;}

        if (imagemotionLock){
            if ((imagemotionQuery.length < 1) && imagecheckTime()){
                imagemotionQuery.push('left');
            }
            return false;
        }
        if (this.position == 0){
            this.position = (this.count);
            $('image-scroll-line').style.left = '-' + (this.position * this.pixScroll)  + 'px';
        }
        imagemotionLock = true;
        jQuery('div#image-scroll-line').animate({left: '+=' + this.pixScroll + 'px'}, this.speed, function() {imagerunSleepedMotion();});
        this.position --;
        this.updatePager();
    },
    scrollToAnchor: function(id, left) {
        if (imagemotionLock){return false;}
        jQuery('div#image-scroll-line').animate({left: '-' + (left * this.perPage * this.pixScroll) + 'px'}, this.speed, function() {});
        if (this.currentId == undefined){
            jQuery('a.first').removeClass('active');
        } else {
            jQuery('a#'+this.currentId).removeClass('active');
        }
        this.currentId = id;
        jQuery('a#'+id).addClass('active');
        this.page = left;
        this.position = left * this.perPage;
    },
    updatePager: function(){
        page = (this.position - (this.position % this.perPage)) / this.perPage ;
        if (this.currentId == undefined){
            if (page == 0){
                return false;
            }
        } else {
            if (this.currentId == 'image-page-button-' + page){
                return false;
            }
        }
        if (this.currentId == undefined){
            jQuery('a#image-page-button-0').removeClass('active');
        } else {
            jQuery('a#'+this.currentId).removeClass('active');
        }
        this.currentId = 'image-page-button-' + page;
        jQuery('a#image-page-button-' + page).addClass('active');
    },
    /* Rates Logic */
    mouseOut: function(obj){
        $('image-aw-rate-indicator').style.width = this.images[this.rateId]['rate'] + '%';
    },
    mouseClick: function(num){
        if (this.images[this.rateId]['can_rate'] == 1){
            //SSL correct work fix
            this.ajaxUrl = this.ajaxUrl.replace(/^http[s]{0,1}/, window.location.href.replace(/:[^:].*$/i, ''));
            var param = 'id/' + this.images[this.rateId]['entity_id'] + '/';
            param += 'rate/' + num + '/';
            $('image-aw-rate-loader').style.display = 'block';
            this.images[this.rateId]['can_rate'] = 0;
            jQuery('div#image-aw-rate-box').addClass('disabled');
            new Ajax.Request(this.ajaxUrl + param, {
                method: 'get',
                onSuccess: function(transport) {                    
                    if (transport && transport.responseText){
                        try{
                            response = eval('(' + transport.responseText + ')');
                            if (response.newrate) {                                
                                $('image-aw-rate-indicator').style.width = response.newrate + '%';
                                $('image-aw-rate-loader').style.display = 'none';
                                $('image-aw-rate-notice').style.display = 'block';
                                imagetest.images[imagetest.rateId]['rate'] = response.newrate;
                            }
                            if (response.error){
                                console.debug(response.error);
                            }
                        }
                        catch (e) {
                            response = {};
                        }
                    }  
                },
                onFailure: function() {
                    $('image-aw-rate-loader').style.display = 'none';
                }
            });            
        }        
    },
    mouseMove: function(num){
        if (this.images[this.rateId]['can_rate'] == 1){
            $('image-aw-rate-indicator').style.width = (num * 20) + '%';
        }
    },

    addImage: function(id, p_url, rate, can_rate, title, details, date, entity_id){
        this.images[id] = {
            id: id,
            p_url: p_url,
            rate: rate,
            can_rate: can_rate,
            title: title,
            details: details,
            date: date,
            entity_id: entity_id
        };
    },
    playImage: function(id){
        if (this.images[id] == 'undefined'){
            return;
        }
        if (this.formShow){
            this.toogleForm();
        }

        player = this.getPlayerHtml(this.images[id]['p_url']);
        $('image-player-content').innerHTML = player;

        if (this.template == undefined){
            this.template = new Template(this.detailTemplate, this.templateSyntax);
        }
        $('image-details-content').innerHTML = this.template.evaluate(this.images[id]);

        this.rateId = id;
        if ($('image-aw-rate-indicator') != undefined){
            $('image-aw-rate-indicator').style.width = this.images[this.rateId]['rate'] + '%';
            $('image-aw-rate-notice').style.display = 'none';
            if (this.images[this.rateId]['can_rate'] == '1'){
                $('image-aw-rate-box').removeClassName('disabled');
            } else {
                $('image-aw-rate-box').addClassName('disabled');
            }
        }
    },
    getPlayerHtml: function(url){
       
        var str = '<img src="'+url+'" />';
        
        return str;
    }
}




